package com.vast.admin.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.vast.system.exception.BusinessException;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.Calendar;
import java.util.List;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.vast.admin.entity.ContractNo;
import com.vast.admin.mapper.ContractNoMapper;
import org.springframework.transaction.annotation.Transactional;

@Service
public class ContractNoService extends ServiceImpl<ContractNoMapper, ContractNo> {

    /**
     * 获取下一个合同编号
     * @param code
     * @return
     */
    @Transactional
    public String getContractNo(String code) {
        Integer year = Calendar.getInstance().get(Calendar.YEAR);
        Integer currentNum = getCurrentNum(code, year);
        if (currentNum == null) {
            currentNum = 1;
        } else {
            currentNum ++;
        }
        int i = 0;
        while (!saveCurrentNum(code, year, currentNum)) {
            currentNum ++;
            i ++;
            if (i > 10) {
                throw new BusinessException("获取合同编号失败");
            }
        }
        return "ZFW-" + code.toUpperCase() + "-" + year + String.format("%06d", currentNum);
    }

    /**
     * 获取当前合同编号
     * @param code
     * @param year
     * @return
     */
    private Integer getCurrentNum(String code, Integer year) {
        QueryWrapper<ContractNo> contractNoQueryWrapper = new QueryWrapper<>();
        contractNoQueryWrapper.select(ContractNo.COL_NUM)
                .eq(ContractNo.COL_CODE, code)
                .eq(ContractNo.COL_YEAR, year);
        List<ContractNo> contractNos = super.list(contractNoQueryWrapper);
        if (contractNos != null && !contractNos.isEmpty()) {
            return contractNos.get(0).getNum();
        } else {
            return null;
        }
    }

    /**
     * 保存合同编号
     * @param code
     * @param year
     * @param currentNum
     */
    private boolean saveCurrentNum(String code, Integer year, Integer currentNum) {
        if (currentNum <= 0) {
            throw new BusinessException("错误的合同编号");
        }
        if (currentNum == 1) {
            ContractNo contractNo = new ContractNo();
            contractNo.setCode(code);
            contractNo.setYear(year);
            contractNo.setNum(1);
            return super.save(contractNo);
        } else {
            UpdateWrapper<ContractNo> contractNoUpdateWrapper = new UpdateWrapper<>();
            contractNoUpdateWrapper.set(ContractNo.COL_NUM, currentNum)
                    .eq(ContractNo.COL_CODE, code)
                    .eq(ContractNo.COL_YEAR, year)
                    .eq(ContractNo.COL_NUM, currentNum - 1);
            return super.update(contractNoUpdateWrapper);
        }
    }
}
